#include "XSystem/XCore.h"

using namespace std;

// Set the data to default value.
XWidget::XWidget(XResourcesManager *data, int width, int height, int positionX, int positionY)
{
	x_app = data->GetApp();
	x_data = data;
	x_width = width;
	x_height = height;
	x_positionX = positionX;
	x_positionY = positionY;
	x_startingPositionX = positionX;
	x_startingPositionY = positionY;
	x_visible = true;
	x_mouseIn = false;
	x_mousePressed = false;
	x_focus = XG_FOC_NO;
	x_state = XG_ST_NONE;
	x_draw = true;
}

//  Check the state of the widget.
void XWidget::CheckState(const sf::Input &input)
{
	int state = XG_ST_NONE;

	if (!x_visible)
	{
		x_state = XG_ST_NONE;
		return;
	}

	unsigned int mouseX = input.GetMouseX();
	unsigned int mouseY = input.GetMouseY();
	bool mousePressed = input.IsMouseButtonDown(sf::Mouse::Left);

	if (int(mouseX) > x_positionX && int(mouseX) < (x_positionX + x_width) && int(mouseY) > x_positionY && int(mouseY) < (x_positionY + x_height))
	{
		if (mousePressed && !x_mousePressed)
		{
			x_mousePressed = true;
			state = XG_ST_LBUTTON_DOWN;

		} else if (!mousePressed && x_mousePressed)
		{
			x_mousePressed = false;
			state = XG_ST_LBUTTON_RELEASED;

			if (x_focus == XG_FOC_NO)
				x_focus = XG_FOC_GAINED;
		}

		if (!x_mouseIn)
		{
			x_mouseIn = true;
			state = XG_ST_MOUSE_ENTER;
		}

	} else {

		if (x_mouseIn)
		{
			x_mouseIn = false;
			state = XG_ST_MOUSE_EXIT;
		}
	}
	
	x_state = state;
}

// \void
void XWidget::CheckEvent(const sf::Event &Event)
{

}

// \void
void XWidget::Draw()
{

}

// Return the focus state
int XWidget::focus()
{
	return x_focus;
}

// Set the focus state
void XWidget::SetFocus(bool focus)
{
	if (focus)
		x_focus = XG_FOC_YES;
	else
		x_focus = XG_FOC_NO;
}

// Set if the widget needs to be drawn
void XWidget::SetDraw(bool draw)
{
	x_draw = draw;
}

// \return the type of the widget
int XWidget::type()
{
	return x_type;
}

// \return the state of the widget
int XWidget::state()
{
	return x_state;
}

// Set the state of the widget manually
void XWidget::SetState(int state)
{
	x_state = state;
}

// Set the position after a window position change
void XWidget::Move(int positionX, int positionY)
{
	x_positionX = x_startingPositionX + positionX;
	x_positionY = x_startingPositionY + positionY;
}

// Set the position of a widget within a window
void XWidget::SetPosition(int positionX, int positionY)
{
	x_positionX = positionX;
	x_positionY = positionY;
}